package example.hello_security.config.handler;

import cn.hutool.json.JSONUtil;
import example.hello_security.config.JwtConfig;
import example.hello_security.config.WebConfig;
import example.hello_security.result.Result;
import example.hello_security.service.RedisStore;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;


/**
 * description 自定义登录结束的处理器handler，不执行默认的springSecurity的逻辑，
 * 原本的逻辑会执行一次redirect，所以需要改写，同时
 * redis中的token令牌也需要进行删除
 * @author zken
 * CreateDate 2024/10/27 22:54:48
 */
@Component
public class CustomLogoutSuccessHandler implements LogoutSuccessHandler {
    @Resource
    WebConfig webConfig;
    @Resource
    JwtConfig jwtConfig;
    @Resource
    RedisStore redisStore;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String token = request.getHeader(webConfig.getTokenName());
        if (StringUtils.isNotBlank(token)) {
            String key = jwtConfig.jwtRedisKeyPrefix + token;
            // 删除redis记忆
            redisStore.remove(key);
        }
        Result<String> result = Result.success("注销成功");
        String json = JSONUtil.toJsonStr(result);
        response.getWriter().write(json);
    }
}
